import React, { useCallback, useState, useEffect } from 'react'
import { Image } from '@tarojs/components'
import DBConfig from '@CONFIG/DBConfig'
import Images from '@ASSET/Images'
import './UserAvatar.scss'

export default function UserAvatar({
  data = {}, avatarStyle = '', onClick, defaultUrl
}) {
  const { AvatarFileName, AvatarVersion, p8Id } = data || {}
  const [source, setSource] = useState(Images.avatar)

  useEffect(() => {
    if ((!AvatarFileName && !p8Id) || !AvatarVersion) {
      setSource(Images.avatar)
      return
    }
    const url = AvatarFileName || `${p8Id}.jpg`
    const staticUrl = AvatarFileName ? DBConfig.staticDoctorAvatarUrl : DBConfig.staticAvatarUrl
    setSource(`${staticUrl}${url}?t=${AvatarVersion}`)
  }, [AvatarFileName, p8Id, AvatarVersion])

  const onError = useCallback(() => {
    setSource(defaultUrl || Images.avatar)
  }, [defaultUrl])
  return (
    <Image
      src={source}
      className={`userAvatar ${avatarStyle}`}
      onClick={onClick}
      onError={onError}
      mode="aspectFill"
    />
  )
}

UserAvatar.defaultProps = {
  onClick: () => {},
  defaultUrl: '',
}
